package com.gitee.lougnib.simple.mybatis.interceptor;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.time.StopWatch;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 输出 SQL 的执行时间到日志中。
 *
 * @author lougnib@163.com
 * @since 2021/07/23
 * @version 2021/07/23
 */
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }),
        @Signature(type = Executor.class, method = "queryCursor", args = { MappedStatement.class, Object.class, RowBounds.class }),
        @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class })
})
public class ExecutorTimeLogInterceptor implements Interceptor {

	/** 日志 */
	private static final Logger LOGGER = LoggerFactory.getLogger(ExecutorTimeLogInterceptor.class);

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		StopWatch stopWatch = StopWatch.createStarted();
		try {
			return invocation.proceed();
		} finally {
			stopWatch.stop();
			MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
			LOGGER.info("{} 执行时间：{} 毫秒", mappedStatement.getId(), stopWatch.getTime(TimeUnit.MILLISECONDS));
		}
	}

}
